<?php
declare (strict_types = 1);
namespace app\api\controller;

use app\BaseController;
use think\facade\{Db, Cache, Log};

use app\api\model\{Users};

class NewsController extends BaseController
{
    /** 消费提醒 */
    public function news_consume($user_id, $admin_id, $type_id, $type = 2, $money = 0)
    {
        $user_info  = Db::name('users')->where(['id' => $user_id])->find();
        $admin_info = Db::name('admin')->where(['id' => $admin_id])->find();
        $card_info = Db::name('user_card')->where(['id' => $type_id])->find();
        $user_shop_info = Db::name('user_shop')->where(['user_id' => $user_id, 'admin_id' => $admin_id])->find();

        /** type=1 次卡核销， type=2 购买商品 */
        if($type == 1){
            $goods_id = $card_info['goods_id'];
        }else{
            $goods_id = $type_id;
        }

        $goods_info = Db::name('goods')->where(['id' => $goods_id])->find();

        $openid       = $user_info['openid2'];
        $access_token = $this->getaccesstoken2();

        $msg = '尊敬的' . $user_info['nickname'] . '，今天您体验了' . $goods_info['title'] . '项目。';

        $point = 0;

        if($type == 1){
            $msg .= '该服务还剩余' . $card_info['card_number'] . '次。';
            $pay_type = '次卡核销';
        }else if($type == 2){
            $msg .= '消费了' . $money . '元，您的余额还有' . $user_shop_info['card_money'] . '元。';
            $pay_type = '商品消费';
            $point = round($money * $admin_info['point_radio'], 2);
        }else{
            $msg .= '消费了' . $money . '元，您的余额还有' . $user_shop_info['money_gold'] . '元。';
            $pay_type = '福利金消费';
        }
        
        $data = [
            'touser'       => $openid,
            'template_id'  => 'WP5t9ZgCRGNakE7dHzwhjsOVWxiyZbzlF-LqFwMtDWg',
            'topcolor'     => '#FF0000',
            'data'         => array(
                'first'    => array('value' => $msg, 'color' => "#E935C9"),
                'time'     => array('value' => date("Y-m-d H:i:s"), 'color' => "#E935C9"),
                'org'      => array('value' => $admin_info['nickname'], 'color' => "#E935C9"),
                'type'     => array('value' => $pay_type,'color' => "#E935C9"),
                'money'    => array('value' => '￥' . $money, 'color' => "#E935C9"),
                'point'    => array('value' => $point, 'color' => "#E935C9"),
                'remark'   => array('value' => "", 'color' => "#E935C9"),
            )
        ];

        $json_data = json_encode($data);
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;

        $res = curl_post($url, urldecode($json_data));
        $res = json_decode($res, true);

        if($res['errcode'] == 0 && $res['errcode'] == "ok"){
            return 'ok';
        }else if($res['errcode'] == 40003){
            return 'ok';
        }else{
            Log::write($res);
            $this->news_consume($user_id, $admin_id, $type_id, $type, $money);
        }
    }

    /** 佣金提醒 */
    public function news_money($user_id, $from_user_id, $goods_id, $money = 0, $type = 1)
    {
        $user_info  = Db::name('users')->where(['id' => $user_id])->find();
        $from_user_info  = Db::name('users')->where(['id' => $from_user_id])->find();
        $goods_info = Db::name('goods')->where(['id' => $goods_id])->find();

        $openid       = $user_info['openid2'];
        $access_token = $this->getaccesstoken2();

        if($type == 1){
            $msg = '尊敬的' . $user_info['nickname'] . '，你的好友' . $from_user_info['nickname'] . '已成功体验' . $goods_info['title'] . '项目！恭喜你获得' . $money . '元推荐奖励！';
        }else{
            $msg = '尊敬的' . $user_info['nickname'] . '，你的好友' . $from_user_info['nickname'] . '已成功购买' . $goods_info['title'] . '项目！恭喜你获得' . $money . '元销售奖励！';
        }

        $data = [
            'touser'       => $openid,
            'template_id'  => 'i1fbg1pCXjnkab8jklNcapXTBgZuF83wO8O168JkA2w',
            'topcolor'     => '#FF0000',
            'data'         => array(
                'first'    => array('value' => $msg, 'color' => "#E935C9"),
                'keyword1' => array('value' => '￥' . $money, 'color' => "#E935C9"),
                'keyword2' => array('value' => date("Y-m-d H:i:s"), 'color' => "#E935C9"),
                'remark'   => array('value' => "", 'color' => "#E935C9"),
            )
        ];

        $json_data = json_encode($data);
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;

        $res = curl_post($url, urldecode($json_data));
        $res = json_decode($res, true);

        if($res['errcode'] == 0 && $res['errcode'] == "ok"){
            return 'ok';
        }else if($res['errcode'] == 40003){
            return 'ok';
        }else{
            Log::write($res);
            $this->news_money($user_id, $from_user_id, $goods_id, $money, $type);
        }
    }

    /** 激活提醒 */
    public function news_activate($user_id, $from_user_id, $admin_id)
    {
        $user_info  = Db::name('users')->where(['id' => $user_id])->find();
        $from_user_info  = Db::name('users')->where(['id' => $from_user_id])->find();
        $admin_info = Db::name('admin')->where(['id' => $admin_id])->find();

        $openid       = $user_info['openid2'];
        $access_token = $this->getaccesstoken2();

        $msg = '恭喜您的朋友' . $from_user_info['nickname'] . '获得了' . $admin_info['nickname'] . '店福利卡' . $admin_info['money_gold'] . '元,他的联系电话' . $from_user_info['phone'] . '。';

        $data = [
            'touser'       => $openid,
            'template_id'  => 'Ldp-P2fLOxeIZR4xqgRwQyaInN5FnHzVjxIukntr73g',
            'topcolor'     => '#FF0000',
            'data'         => array(
                'first'    => array('value' => $msg, 'color' => "#E935C9"),
                'keyword1' => array('value' => date("Y-m-d H:i:s"), 'color' => "#E935C9"),
                'keyword2' => array('value' => $from_user_info['nickname'], 'color' => "#E935C9"),
                'remark'   => array('value' => "", 'color' => "#E935C9"),
            )
        ];

        $json_data = json_encode($data);
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;

        $res = curl_post($url, urldecode($json_data));
        $res = json_decode($res, true);

        if($res['errcode'] == 0 && $res['errcode'] == "ok"){
            return 'ok';
        }else if($res['errcode'] == 40003){
            return 'ok';
        }else{
            Log::write($res);
            $this->news_activate($user_id, $from_user_id, $admin_id);
        }
    }

    /** 充值提醒 */
    public function news_recharge($user_id, $admin_id, $money)
    {
        $user_info  = Db::name('users')->where(['id' => $user_id])->find();
        $user_shop_info = Db::name('user_shop')->where(['user_id' => $user_id, 'admin_id' => $admin_id])->find();

        $openid       = $user_info['openid2'];
        $access_token = $this->getaccesstoken2();

        $msg = '尊敬的' . $user_info['nickname'] . ':';

        $data = [
            'touser'       => $openid,
            'template_id'  => 'l-yzFZFIEYcBvpyNMY3XYTFraVVFCm4KSYRcsoI0MG8',
            'topcolor'     => '#FF0000',
            'data'         => array(
                'first'    => array('value' => $msg, 'color' => "#E935C9"),
                'keyword1' => array('value' => '￥' . $money, 'color' => "#E935C9"),
                'keyword2' => array('value' => '￥' . $user_shop_info['card_money'], 'color' => "#E935C9"),
                'keyword3' => array('value' => date("Y-m-d H:i:s"), 'color' => "#E935C9"),
                'remark'   => array('value' => "", 'color' => "#E935C9"),
            )
        ];

        $json_data = json_encode($data);
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;

        $res = curl_post($url, urldecode($json_data));
        $res = json_decode($res, true);

        if($res['errcode'] == 0 && $res['errcode'] == "ok"){
            return 'ok';
        }else if($res['errcode'] == 40003){
            return 'ok';
        }else{
            Log::write($res);
            $this->news_recharge($user_id, $admin_id, $money);
        }
    }

    /** 预约提醒 */
    public function news_make($user_id, $to_user_id, $order_id)
    {
        $user_info  = Db::name('users')->where(['id' => $user_id])->find();
        $to_user_info  = Db::name('users')->where(['id' => $to_user_id])->find();
        $order_info  = Db::name('order_make')->where(['id' => $order_id])->find();
        $goods_info  = Db::name('goods')->where(['id' => $order_info['goods_id']])->find();
        $techn_time_info  = Db::name('techn_time')->where(['id' => $order_info['techn_time_id']])->find();

        $openid       = $user_info['openid2'];
        $access_token = $this->getaccesstoken2();

        $msg = '您的顾客' . $to_user_info['nickname'] . '，预约了' . $goods_info['title'] . '项目, 预约时间为' . date('Y年m月d日', $order_info['make_time']) . ' ' . $techn_time_info['time_name'];

        $data = [
            'touser'       => $openid,
            'template_id'  => 'L4l4uB7IVH2Ydzm-Z_TWgbuf9chSg-RPs7G50JnHaKo',
            'topcolor'     => '#FF0000',
            'data'         => array(
                'first'    => array('value' => $msg, 'color' => "#E935C9"),
                'keyword1' => array('value' =>  date("Y-m-d H:i:s"), 'color' => "#E935C9"),
                'keyword2' => array('value' => $to_user_info['nickname'], 'color' => "#E935C9"),
                'keyword3' => array('value' => $to_user_info['phone'], 'color' => "#E935C9"),
                'remark'   => array('value' => "", 'color' => "#E935C9"),
            )
        ];

        $json_data = json_encode($data);
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;

        $res = curl_post($url, urldecode($json_data));
        $res = json_decode($res, true);

        if($res['errcode'] == 0 && $res['errcode'] == "ok"){
            return 'ok';
        }else if($res['errcode'] == 40003){
            return 'ok';
        }else{
            Log::write($res);
            $this->news_make($user_id, $to_user_id, $order_id);
        }
    }

    /** 服务完成提醒 */
    public function news_service($user_id, $to_user_id, $goods_id)
    {
        $user_info  = Db::name('users')->where(['id' => $user_id])->find();
        $to_user_info  = Db::name('users')->where(['id' => $to_user_id])->find();
        $goods_info  = Db::name('goods')->where(['id' => $goods_id])->find();

        $openid       = $user_info['openid2'];
        $access_token = $this->getaccesstoken2();

        $msg = '尊敬的' . $user_info['nickname'] . '，今天为' . $to_user_info['nickname'] . '服务了' . $goods_info['title'] . '项目。';

        $data = [
            'touser'       => $openid,
            'template_id'  => 'noPTySUnEgcMhNLD4TUOYO7227vVMQODt5HK7SHcrlk',
            'topcolor'     => '#FF0000',
            'data'         => array(
                'first'    => array('value' => $msg, 'color' => "#E935C9"),
                'keyword1' => array('value' => $goods_info['title'], 'color' => "#E935C9"),
                'keyword2' => array('value' => date("Y-m-d H:i:s"), 'color' => "#E935C9"),
                'remark'   => array('value' => "", 'color' => "#E935C9"),
            )
        ];

        $json_data = json_encode($data);
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;

        $res = curl_post($url, urldecode($json_data));
        $res = json_decode($res, true);

        if($res['errcode'] == 0 && $res['errcode'] == "ok"){
            return 'ok';
        }else if($res['errcode'] == 40003){
            return 'ok';
        }else{
            Log::write($res);
            $this->news_service($user_id, $to_user_id, $goods_id);
        }
    }

    /** 获取access_token(模板消息) */
    public function getaccesstoken2()
    {
        $appid     = 'wx32e802da159d88d4';
        $appsecret = '1c1e887fa34ebd536b9d64e5f6b16e42';

        $access_token = Cache::get('wx_access_token:' . $appid);

        if($access_token){
            return $access_token;
        }else{
            //1.请求url地址
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";

            $res = curl_get($url);
            $res = json_decode((string)$res, true);

            if(isset($res['errcode']) && $res['errcode'] != 0){
                Log::write('AccessTokenError,ErrCode:'.$res['errcode'].',ErrMsg:'.$res['errmsg']);
            }

            $access_token = $res['access_token'];
            Cache::tag('accessToken')->set('wx_access_token:' .  $appid, $access_token, 3600);

            return $access_token;
        }  
    }
    
    /** 用于第一次验证我们网站url合法性 */
    public function firstValid(){
        //检验签名的合法性
        if($this->_checkSignature()){
            //签名合法，告知微信公众平台服务器
            echo $_GET['echostr'];
        }
    }

    /** 验证签名 */
    private function _checkSignature(){
        //获得由微信公众平台请求的验证数据
        $signature = $_GET['signature'];
        $timestamp = $_GET['timestamp'];
        $nonce     = $_GET['nonce'];

        //将时间戳，随机字符串，token按照字母顺序排序，并连接
        $tmp_arr = array('AAA123456', $timestamp, $nonce);
        
        sort($tmp_arr, SORT_STRING);  // 字典顺序
        $tmp_str = implode($tmp_arr);  // 连接
        $tmp_str = sha1($tmp_str);  // sha1加密

        if($signature == $tmp_str){
            $this->responseMsg();
        }else{
            return false;
        }
    }

    /** 公众号事件 */
    public function responseMsg(){
        /** 接收微信返回的数据数据,返回的xml格式 */
        $data = file_get_contents('php://input');

        /** 将xml格式转换为数组 */
        $data = $this->xmlToArray($data);

        if(!isset($data['MsgType'])){
            return true;
        }

        if($data['MsgType'] == 'event'){
            if($data['Event'] == 'subscribe'){  /** 关注事件 */
                $this->doSubscribe($data['FromUserName']);
            }else if($data['Event'] == 'unsubscribe'){  /** 取关事件 */
                $this->unsubscribe($data['FromUserName']);
            }    
        }

        return true;
    }

    /** 关注后做的事件 */
    private function doSubscribe($openid){
        $access_token = $this->getaccesstoken2();

        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid={$openid}&lang=zh_CN";
        $res = curl_get($url);

        $res = json_decode((string)$res, TRUE);
        
        if(!isset($res['errcode'])){
            $userModel = new Users();
            $user_info = $userModel->getFind(['unionid' => $res['unionid']]);

            if($user_info['code'] == 'ok'){
                $userModel->edit(['id' => $user_info['data']['id'], 'openid2' => $openid, 'is_follow' => 1]);
            }
        }
    }

    /** 取消关注后做的事件 */
    private function unsubscribe($openid){
        $userModel = new Users();
        $user_info = $userModel->getFind(['openid2' => $openid]);

        if($user_info['code'] == 'ok'){
            $userModel->edit(['id' => $user_info['data']['id'], 'is_follow' => 0]);
        }
    }

    //xml转换成数组
    private function xmlToArray($xml)
    {
        //禁止引用外部xml实体
        // libxml_disable_entity_loader(true);
        $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $val = json_decode(json_encode($xmlstring), true);

        return $val;
    }
}